import NProgress from 'nprogress'
import request from '@/utils/request'

function myBrowser() {
  var userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
  var isOpera = userAgent.indexOf('Opera') > -1
  if (isOpera) {
    return 'Opera'
  } // 判断是否Opera浏览器
  if (userAgent.indexOf('Firefox') > -1) {
    return 'FF'
  } // 判断是否Firefox浏览器
  if (userAgent.indexOf('Chrome') > -1) {
    return 'Chrome'
  }
  if (userAgent.indexOf('Safari') > -1) {
    return 'Safari'
  } // 判断是否Safari浏览器
  if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
    return 'IE'
  } // 判断是否IE浏览器
  if (userAgent.indexOf('Trident') > -1) {
    return 'Edge'
  } // 判断是否Edge浏览器
}
function SaveAs5(imgURL) {
  var oPop = window.open(imgURL, '', 'width=1, height=1, top=5000, left=5000')
  for (; oPop.document.readyState !== 'complete'; ) {
    if (oPop.document.readyState === 'complete') break
  }
  oPop.document.execCommand('SaveAs')
  oPop.close()
}
function download(src, fileName = '') {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement('a')
  if (fileName) {
    eleLink.setAttribute('download', fileName)
  } else {
    eleLink.download = src
  }
  eleLink.style.display = 'none'
  // // 字符内容转变成blob地址
  eleLink.href = src
  // // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // // 然后移除
  document.body.removeChild(eleLink)
}
export function isDecodedStr(fileName) {
  let hasInvalidCharacters = false // 初始化一个变量来标识是否存在乱码字符
  for (let i = 0; i < fileName.length; i++) {
    const char = fileName[i]
    const charCode = char.charCodeAt(0)

    // 判断是否是乱码字符的条件
    if (charCode < 32 || (charCode > 126 && charCode < 161)) {
      hasInvalidCharacters = true
      break // 一旦发现乱码字符，立即跳出循环
    }
  }
  return hasInvalidCharacters
}
export function fileDownload(res) {
  const a = document.createElement('a')
  const blob = new Blob([res.data], { type: 'application/octet-stream' }) //, { type: 'application/vnd.ms-excel' }
  const temp = res.headers['content-disposition'].split(';')[1].split('filename=')[1]
  let fileName = temp
  // 判断文件名是否包含乱码字符
  // const isDecoded = Array.from(fileName).every((char) => char.charCodeAt(0) !== 65533)
  const isDecoded = isDecodedStr(fileName)
  if (isDecoded) {
    // 对文件名乱码转义--【Node.js】使用iconv-lite解决中文乱码
    const iconv = require('iconv-lite')
    iconv.skipDecodeWarning = true // 忽略警告
    fileName = iconv.decode(temp, 'utf-8')
  }

  a.setAttribute('download', fileName)
  const objectUrl = URL.createObjectURL(blob)

  a.setAttribute('href', objectUrl)
  a.click()
}
export function downLoadFileFromServer(data){
  return request({
    url: '/files/download',
    method: 'post',
    data
  })
}
export function downLoadFile(url, fileName = '') {
  if (myBrowser() === 'IE' || myBrowser() === 'Edge') {
    SaveAs5(url)
  } else {
    download(url, fileName)
  }
}
